package net.wanho.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * Author：汤小洋
 * Date：2025-10-22 13:46
 * Description：<描述>
 */
@Configuration
public class RabbitMqConfig {

    @Value("${shop.exchange}")
    private String exchange;

    @Value("${shop.queue}")
    private String queue;

    @Value("${shop.routingKey}")
    private String routingKey;

    @Bean
    public Exchange exchange(){
        return new DirectExchange(exchange);
    }

    @Bean
    public Queue queue(){
        return new Queue(queue);
    }

    @Bean
    public Binding binding(Exchange exchange, Queue queue){
        return BindingBuilder.bind(queue).to(exchange).with(routingKey).noargs();
    }

    /**
     * 消息转换器
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        // 设置消息确认的回调函数
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if(ack){
                System.out.println("成功，消息已到达交换机。。。。。");
            }else{
                System.out.println("失败，消息未到达交换机。。。。。");
            }
        });

        // 设置消息回退的回调函数
        rabbitTemplate.setReturnsCallback(returned -> {
            //
            System.out.println("失败，消息未到达队列。。。。。" + returned.getReplyCode() + "，" + returned.getReplyText()); // 响应码和响应信息
        });
    }


}
